package com.cangshi.filter;


import com.alibaba.fastjson.JSON;
import com.cangshi.entity.Bill;
import com.cangshi.entity.Group;
import com.cangshi.entity.Order;
import com.cangshi.entity.User;
import com.cangshi.service.BillService;
import com.cangshi.service.GroupService;
import com.cangshi.service.GroupUserService;
import com.cangshi.service.OrderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by user on 2016-12-9.
 */
public class GroupFilter implements Filter {

    @Autowired
    GroupService groupService;

    @Autowired
    GroupUserService groupUserService;

    @Autowired
    BillService billService;

    @Autowired
    OrderService orderService;

    private static final Logger LOGGER = Logger.getLogger(LoginFilter.class);

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        LOGGER.debug("-------->开始检测团存活日期");

        //获取所有拼团中的团
        Group checkGroup = new Group();
        checkGroup.setGroupStatus(0);
        List<Group> groups = groupService.findGroupsByGroup(checkGroup, null, null);
        LOGGER.debug("-------->" + JSON.toJSON(groups));

        //遍历获取的团列表，核对存在时间
        if (groups == null || groups.isEmpty()) {
            LOGGER.debug("-------->没有符合条件的团");
            filterChain.doFilter(servletRequest, servletResponse);

        } else {
            for (Group group : groups) {

                if(group.getGroupAliveHours()==-1){
                    continue;
                }

                //获取团相关时间戳
                Long requestTime = (long) group.getGroupAliveHours() * 60 * 60 * 1000;
                Long checkTime = group.getGroupInitTime().getTime();
                Long nowTime = new Date().getTime();

                Long resultTime = requestTime - (nowTime - checkTime);

                //检查团存活时间
                if (resultTime < 0) {
                    Group changeGroup = new Group();
                    changeGroup.setGroupId(group.getGroupId());
                    changeGroup.setGroupStatus(2);

                    groupService.updateGroup(changeGroup);

                    LOGGER.debug("-------->团id:" + group.getGroupId() + "   已过期");

                    //获得该团所有用户
                    List<User> users = groupUserService.getAllUsersByGroupId(group.getGroupId());
                    if(!users.isEmpty()){

                        for(User eachUser:users) {
                            //退款
                            //创建账单
                            Bill bill = new Bill();
                            bill.setUserId(eachUser.getUserId());
                            bill.setBillChangeValue(group.getGroupPrice() + group.getGroupPostage());
                            bill.setBillChangeType(1);
                            bill.setBillOrigin("参团商品失效退款");
                            bill.setBillInfo("参团id:" + group.getGroupId() + ",商品价格：￥" + group.getGroupPrice() + ",邮费：￥" + group.getGroupPostage());
                            //获取账单生成结果
                            Integer resultForBill = billService.addBill(bill);
                        }

                    }

                    //获取该团所有订单
                    List<Order> orders = orderService.findByGroupId(group.getGroupId());
                    if(!orders.isEmpty()){
                        for(Order eachOrder:orders) {
                            //取消订单（修改订单状态）
                            Order checkOrder = new Order();
                            checkOrder.setOrderId(eachOrder.getOrderId());
                            checkOrder.setOrderStatus(-1);
                            //提交修改
                            Integer resultForOrder = orderService.modifyOrder(checkOrder);
                        }
                    }

                    continue;
                }

                //打印剩余时间
                //格式化剩余时间
                LOGGER.debug("-------->"+resultTime);
                    //获取小时
                    Long hours = resultTime/3600000;
                    //分钟
                    Long min = resultTime%3600000/60000;
                    //秒
                    Long s = requestTime%3600000%60000/1000;
                DateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                LOGGER.debug("-------->团id:" + group.getGroupId() + "  剩余时间 " + hours + ":" + min + ":" + s);

            }

            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    public void destroy() {

    }
}
